var _modulos = Array();
_modulos["UI"] 			= {dependencias:'ui.core.js',cargado:false};
_modulos["Form"]		= {dependencias:'jquery.form.js,jquery.validar.js',cargado:false};
_modulos["Encoding"]            = {dependencias:'',cargado:false};
_modulos["Path"]		= {dependencias:'',cargado:false};	
_modulos["Cookie"]		= {dependencias:'jquery.cookie.js',cargado:false};

JS= function()
{
    _carpeta : '';
	
    return {
	cargarDependencias: function (p_modulo){

            if (p_modulo.dependencias)
            {
                    dependencias = p_modulo.dependencias.split(',');

                    for (j in dependencias)
                    {
                            log('<-ini:' + dependencias[j] + '-->');
                            $.include(JS._carpeta + '/modulos/dependencias/' + dependencias[j]);
                            log('<-fin:' + dependencias[j] + '-->');
                    }

            }
            p_modulo.cargado = true;

        },
		
        cargarModulos: function(p_carpeta,p_modulos)
		{
			JS._carpeta = p_carpeta;
			var modulos = (p_modulos ? p_modulos : '') ;		
		
			if (modulos)
			{
				/*
				if (!_modulos["Jquery"].cargado)
				{
					
					dependencias = _modulos["Jquery"].dependencias.split(',');
					
					for (j in dependencias)
					{
						log(dependencias[j]);
						fileref=document.createElement('script');
						fileref.setAttribute("type","text/javascript");
						fileref.setAttribute("src", "js/modulos/dependencias/"+dependencias[j]);
						document.getElementsByTagName("head")[0].appendChild(fileref);
					}
					_modulos["Jquery"].cargado = true;
				}
				*/
				mods = modulos.split(',');
				
				for (i=0 ; i < mods.length; i++)
				{
					log(mods[i]);
					if (_modulos[mods[i]])
					{
							log('<-ini:' + mods[i]+ '-->');
							$.include(p_carpeta + '/modulos/JS_' + mods[i] + '.js');
							//_modulos[mods[i]].cargado = true;
							log('<-fin:' + mods[i] + '-->');
							JS.cargarDependencias(_modulos[mods[i]]);
//							if (_modulos[mods[i]].dependencias)
//							{
//								dependencias = _modulos[mods[i]].dependencias.split(',');
//
//								for (j in dependencias)
//								{
//									log('<-ini:' + dependencias[j] + '-->');
//									$.include(p_carpeta + '/modulos/dependencias/' + dependencias[j]);
//									log('<-fin:' + dependencias[j] + '-->');
//								}
//
//							}
						
					}
					
					/*
					switch (mods[i])
					{
						case 'UI':
							log('<-ini:' + mods[i] + '-->');
							$.include('js/JS_' + mods[i] + '.js');
							log('<-fin:' + mods[i] + '-->');

						break;
						case '':
						break;
					}*/
					
				}
				
				return;
			}
		},

		
		redirect: function(ruta, stayIfEmpty)
        {
	    if (ruta==null)
	        ruta = "";
	    if (ruta == "" && stayIfEmpty)
	        return;
            window.location= ruta;
        },
        setCookie: function(arrCookies, opciones)
        {
//            var options = { path: '/', expires: 10 };

            $(arrCookies).each(function(index){
                $.cookie(arrCookies[index].clave, arrCookies[index].valor);
            });
        },

        
        data:
        {
            str:
            {luky: function (array, separador){
                        var response = "";
                        var sep      = separador ? separador : ',';


                        $.each(array,
                                    function(i, l)
                                    {
                                        if (sep.indexOf("@") > -1)
                                            response += sep.replace('@',l);
                                        else
                                            response += l + sep;
                                    }
                        );
                        return response;
                    },
                    fromArray: function(arrEstringuis){
                        var sRetorno= '';

                        if(JS.data.isArray(arrEstringuis))
                        {
                            $.each(arrEstringuis, function(index){
                                sRetorno+= arrEstringuis[index]+ '\n';
                            });
                        }
                        else
                            {
                                sRetorno= arrEstringuis;
                            }

                        return sRetorno;
                    }
            },
            /* [dami] le queria poner boolean pero es una palabra reservada */
            bool:   {parse: function(sValor){
                        if(sValor=== 'true'|| sValor=== true|| parseInt(sValor)> 0)
                        {
                            return true;
                        }
                        else
                            {
                                return false;
                            }
                    }},
            isArray: function(valor)
            {
                if (valor.constructor.toString().indexOf("Array") == -1)
                {
                  return false;
                }
                else
                {
                  return true;
                }
            },
            vacio: function(dato)
            {
                return (dato=== "");
            },
            strPad: function (input, pad_length, pad_string, pad_type)
            {
                var half = '', pad_to_go;

                var str_pad_repeater = function (s, len) {
                    var collect = '', i;

                    while (collect.length < len) {collect += s;}
                    collect = collect.substr(0,len);

                    return collect;
                };

                input += '';
                pad_string = pad_string !== undefined ? pad_string : ' ';

                if (pad_type != 'STR_PAD_LEFT' && pad_type != 'STR_PAD_RIGHT' && pad_type != 'STR_PAD_BOTH') {pad_type = 'STR_PAD_RIGHT';}
                if ((pad_to_go = pad_length - input.length) > 0) {
                    if (pad_type == 'STR_PAD_LEFT') {input = str_pad_repeater(pad_string, pad_to_go) + input;}
                    else if (pad_type == 'STR_PAD_RIGHT') {input = input + str_pad_repeater(pad_string, pad_to_go);}
                    else if (pad_type == 'STR_PAD_BOTH') {
                        half = str_pad_repeater(pad_string, Math.ceil(pad_to_go/2));
                        input = half + input + half;
                        input = input.substr(0, pad_length);
                    }
                }
                return input;
            },
            recortar: function(sTexto, iLargo)
            {
                var sRetorno = sTexto;
                if (sTexto.length > iLargo)
                {
                    sRetorno = sTexto.substring(0, iLargo - 3) + "...";
                }
                return sRetorno;
            }
        },
        html:
        {
            create: function(sTag, valor)
            {
                var retorno = "";

                if(JS.data.isArray(valor))
                {
                    $.each(valor, function(i, l){
                        retorno += '<'+ sTag+'>' + l + '</'+ sTag+'>';
                    });
                }
                else
                    {
                        retorno += '<'+ sTag+'>' + valor + '</'+ sTag+'>';
                    }

                return retorno;
            },
            incluir: function (filename, filetype){
             
                 var fileref;
                 if (filetype=="js"){ //if filename is a external JavaScript file
                  fileref=document.createElement('script')
                  fileref.setAttribute("type","text/javascript")
                  fileref.setAttribute("src", filename)
                 }
                 else if (filetype=="css"){ //if filename is an external CSS file
                  fileref = document.createElement("link")
                  fileref.setAttribute("rel", "stylesheet")
                  fileref.setAttribute("type", "text/css")
                  fileref.setAttribute("href", filename)
                 }
                 if (typeof fileref!="undefined")
                  document.getElementsByTagName("head")[0].appendChild(fileref)
            }
        },
        ajax:{manejar: function(opciones)
                {
                    var opt = $.extend( {fnSuccess: function(data){
                                                //se supone que esto se sobreescrive
                                            },
                                            fnError: function(data){
                                                if(data.mensaje)
                                                {
                                                    this.fnAlerta(  data.mensaje,
                                                                    {destino: data.destino}
                                                    );
                                                    this.fnOnError();
                                                }
                                                else
                                                    {
                                                        if(data.destino)
                                                        {
                                                            JS.redirect(data.destino);
                                                        }
                                                        else
                                                            {
                                                                this.fnAlerta('Error de conexi�n');
                                                            }
                                                    }
                                            },
                                            fnAlerta: function(msj, conf)
                                            {
                                                JS.alert(msj, conf);
                                            },
                                            fnOnError: function()
                                            {

                                            },
                                            fnFinaly:function(){
                                                
                                            }
                                        }, opciones);
                          
                    try
                    {
                        if(opt.data.estado> 0)
                        {
                            opt.fnSuccess(opt.data);
                        }
                        else
                            {
                                opt.fnError(opt.data);
                            }

                        opt.fnFinaly();
                    }
                    catch(err)
                    {
                        JS.alert('Sucedi� un error inesperado');
                        if(console){console.log(err);}
                    }                       
                },
                cargarContenido: function ( opciones )
                {
                    $.ajax({
                       url: opciones.ruta,
                       data: (opciones.datos ? opciones.datos : null),
                       success: function (html){
                           $('#' + opciones.contenedor).html(html);
                           if (opciones.alFinalizar)
                                   opciones.alFinalizar();
                       }
                     });
                }
            }


    };
}();
//***********************************************************************************************************//

if(!("console" in window) || !("firebug" in console)) {
    var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml", "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];

    window.console = {};

    for(var i = 0; i < names.length; ++i) window.console[names[i]] = function() {};
}

function log(msg) {
        if(console)
		console.log(msg);
}

function inspect(obj) {
	if(console)
		console.dir(obj);
}

function debug(obj) {
	if(console)
		console.debug(obj);
}

//***********************************************************************************************************//
/**
 * $.include - script inclusion jQuery plugin
 * Based on idea from http://www.gnucitizen.org/projects/jquery-include/
 * @author Tobiasz Cudnik
 * @link http://meta20.net/.include_script_inclusion_jQuery_plugin
 * @license MIT
 */
// overload jquery's onDomReady
if ( jQuery.browser.mozilla || jQuery.browser.opera ) {
	document.removeEventListener( "DOMContentLoaded", jQuery.ready, false );
	document.addEventListener( "DOMContentLoaded", function(){jQuery.ready();}, false );
}
jQuery.event.remove( window, "load", jQuery.ready );
jQuery.event.add( window, "load", function(){jQuery.ready();} );
jQuery.extend({
	includeStates: {},
	include: function(url, callback, dependency){
		if ( typeof callback != 'function' && ! dependency ) {
			dependency = callback;
			callback = null;
		}
                
		url = url.replace('\n', '');
		jQuery.includeStates[url] = false;
		var script = null;
                if (url.indexOf(".css") > 0)
                {
                    script = document.createElement('link');
                    script.setAttribute("rel", "stylesheet");
                    script.setAttribute("type", "text/css");
                    script.setAttribute("href", url);
                }
                else
                {
                    script = document.createElement('script');
                    script.type = 'text/javascript';
                    script.src = url;
                }

		script.onload = function () {
			jQuery.includeStates[url] = true;
			if ( callback )
				callback.call(script);
		};
		script.onreadystatechange = function () {
			if ( this.readyState != "complete" && this.readyState != "loaded" ) return;
			jQuery.includeStates[url] = true;
			if ( callback )
				callback.call(script);
		};
		
		if ( dependency ) {
			if ( dependency.constructor != Array )
				dependency = [dependency];
			setTimeout(function(){
				var valid = true;
				$.each(dependency, function(k, v){
					if (! v() ) {
						valid = false;
						return false;
					}
				})
				if ( valid )
					document.getElementsByTagName('head')[0].appendChild(script);
				else
					setTimeout(arguments.callee, 10);
			}, 10);
		}
		else
			document.getElementsByTagName('head')[0].appendChild(script);
		return function(){
			return jQuery.includeStates[url];
		}
	},
	readyOld: jQuery.ready,
	ready: function () {
		if (jQuery.isReady) return;
		imReady = true;
		$.each(jQuery.includeStates, function(url, state) {
			if (! state)
				return imReady = false;
		});
		if (imReady) {
			jQuery.readyOld.apply(jQuery, arguments);
		} else {
			setTimeout(arguments.callee, 10);
		}
	}
});